package com.lianjia.analysis.controller.api;

import com.lianjia.analysis.model.HouseInfo;
import com.lianjia.analysis.model.dto.PageDTO;
import com.lianjia.analysis.service.HouseService;
import com.lianjia.analysis.service.impl.HouseServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

@RestController
@RequestMapping("/api/houses")
@Tag(name = "房源API", description = "提供房源数据相关的API")
public class HouseApiController {

    private static final Logger logger = LoggerFactory.getLogger(HouseApiController.class);

    @Autowired
    private HouseService houseService;
    
    /**
     * 获取所有城市列表
     */
    @GetMapping("/cities")
    @Operation(summary = "获取所有城市列表", description = "返回系统中所有可用的城市列表")
    public ResponseEntity<List<String>> getCities() {
        return ResponseEntity.ok(houseService.getAllCities());
    }
    
    /**
     * 获取所有区域列表
     */
    @GetMapping("/districts")
    @Operation(summary = "获取所有区域列表", description = "返回系统中所有城市的区域列表，如果指定城市则返回该城市下的区域列表")
    public ResponseEntity<?> getDistricts(
            @Parameter(description = "城市名称") @RequestParam(required = false) String city) {
        if (city != null && !city.isEmpty()) {
            // 如果指定了城市，返回该城市的区域列表
            Map<String, List<String>> allDistricts = houseService.getAllDistricts();
            List<String> cityDistricts = allDistricts.getOrDefault(city, java.util.Collections.emptyList());
            return ResponseEntity.ok(cityDistricts);
        } else {
            // 如果没有指定城市，返回所有城市的区域列表
            return ResponseEntity.ok(houseService.getAllDistricts());
        }
    }
    
    /**
     * 获取价格区间列表
     */
    @GetMapping("/price-ranges")
    @Operation(summary = "获取价格区间列表", description = "返回系统中预设的价格区间列表")
    public ResponseEntity<List<String>> getPriceRanges() {
        return ResponseEntity.ok(houseService.getPriceRanges());
    }
    
    /**
     * 获取面积区间列表
     */
    @GetMapping("/area-ranges")
    @Operation(summary = "获取面积区间列表", description = "返回系统中预设的面积区间列表")
    public ResponseEntity<List<String>> getAreaRanges() {
        return ResponseEntity.ok(houseService.getAreaRanges());
    }
    
    /**
     * 获取户型列表
     */
    @GetMapping("/layouts")
    @Operation(summary = "获取户型列表", description = "返回系统中所有可用的户型列表")
    public ResponseEntity<List<String>> getLayouts() {
        return ResponseEntity.ok(houseService.getLayouts());
    }
    
    /**
     * 获取装修列表
     */
    @GetMapping("/decorations")
    @Operation(summary = "获取装修列表", description = "返回系统中所有可用的装修类型列表")
    public ResponseEntity<List<String>> getDecorations() {
        return ResponseEntity.ok(houseService.getDecorations());
    }
    
    /**
     * 搜索房源
     */
    @GetMapping
    @Operation(summary = "搜索房源", description = "根据各种条件搜索房源")
    public ResponseEntity<Map<String, Object>> searchHouses(
            @Parameter(description = "城市") @RequestParam(required = false) String city,
            @Parameter(description = "价格区间，格式:minPrice-maxPrice，单位:万元") @RequestParam(required = false) String priceRange,
            @Parameter(description = "面积区间，格式:minArea-maxArea，单位:平方米") @RequestParam(required = false) String areaRange,
            @Parameter(description = "户型") @RequestParam(required = false) String layout,
            @Parameter(description = "装修情况") @RequestParam(required = false) String decoration,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String query,
            @Parameter(description = "排序方式(default,priceAsc,priceDesc,areaAsc,areaDesc)") @RequestParam(defaultValue = "default") String sort,
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size) {
        try {
            logger.info("搜索房源接口调用: city={}, priceRange={}, areaRange={}, layout={}, decoration={}, query={}, sort={}, page={}, size={}",
                    city, priceRange, areaRange, layout, decoration, query, sort, page, size);
            
            // 分页参数处理
            if (page < 0) page = 0;
            if (size <= 0) size = 10;
            if (size > 50) size = 50;  // 限制最大返回条数
            
            // 调用服务进行搜索
            long start = System.currentTimeMillis();
            
            // 直接使用houseService接口方法进行搜索
            PageDTO<HouseInfo> pageResult = houseService.findHouses(
                    city, priceRange, areaRange, layout, decoration, query, sort, page, size);
            
            // 如果没有找到结果，尝试放宽条件
            if (pageResult.getContent().isEmpty() && pageResult.getTotalElements() == 0 && layout != null) {
                logger.info("未找到符合户型条件的房源，尝试忽略户型条件");
                
                // 忽略户型条件，只保留其他条件
                pageResult = houseService.findHouses(
                        city, priceRange, areaRange, null, decoration, query, sort, page, size);
                
                // 如果仍然没有结果，忽略装修条件
                if (pageResult.getContent().isEmpty() && pageResult.getTotalElements() == 0 && decoration != null) {
                    logger.info("未找到符合装修条件的房源，尝试忽略装修条件");
                    pageResult = houseService.findHouses(
                            city, priceRange, areaRange, null, null, query, sort, page, size);
                }
            }
            
            // 构建分页响应
            Map<String, Object> response = new HashMap<>();
            response.put("content", pageResult.getContent());
            response.put("totalElements", pageResult.getTotalElements());
            response.put("totalPages", pageResult.getTotalPages());
            response.put("size", pageResult.getSize());
            response.put("number", pageResult.getNumber());
            
            long end = System.currentTimeMillis();
            logger.info("搜索房源耗时: {}ms, 结果数: {}", (end - start), pageResult.getContent().size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("搜索房源失败: ", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "搜索房源失败: " + e.getMessage());
            errorResponse.put("content", Collections.emptyList());
            errorResponse.put("totalElements", 0);
            errorResponse.put("totalPages", 0);
            errorResponse.put("size", size);
            errorResponse.put("number", page);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 获取房源详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取房源详情", description = "根据ID获取房源详细信息")
    public ResponseEntity<HouseInfo> getHouseDetail(
            @Parameter(description = "房源ID") @PathVariable String id) {
        return ResponseEntity.ok(houseService.findHouseById(id));
    }
    
    /**
     * 获取相似房源
     */
    @GetMapping("/{id}/similar")
    @Operation(summary = "获取相似房源", description = "根据ID获取与该房源相似的其他房源列表")
    public ResponseEntity<List<HouseInfo>> getSimilarHouses(
            @Parameter(description = "房源ID") @PathVariable String id) {
        return ResponseEntity.ok(houseService.findSimilarHouses(id));
    }
    
    /**
     * 获取所有筛选选项
     */
    @GetMapping("/filter-options")
    @Operation(summary = "获取所有筛选选项", description = "返回系统中所有筛选选项，包括城市、价格区间、面积区间、户型、装修等")
    public ResponseEntity<Map<String, Object>> getFilterOptions() {
        Map<String, Object> options = new HashMap<>();
        options.put("cities", houseService.getAllCities());
        options.put("priceRanges", houseService.getPriceRanges());
        options.put("areaRanges", houseService.getAreaRanges());
        options.put("layouts", houseService.getLayouts());
        options.put("decorations", houseService.getDecorations());
        return ResponseEntity.ok(options);
    }
} 